import secrets

from fastapi import Request

def create_session_token(request: Request):
    """
    创建令牌后保存在会话中&返回

    Args:
        request (Request): FastAPI Request 对象

    Returns:
        str: 生成的令牌
    """
    token = secrets.token_hex(16)  # 16创建一个字节令牌
    request.session["ss_token"] = token  # 在会话中保存令牌
    return token

def check_token(request: Request, token: str) -> bool:
    """传递给会话和因素的totin检查功能

    Args:
        request (Request): FastAPI Request 对象
        token (str): token 字符串

    Returns:
        bool: Tokes是否匹配
    """
    if not token:
        return False

    token = token.strip()
    if token == request.session.get("ss_token"):
        # 删除会话 #删除会话
        request.session["ss_token"] = ""
        return True

    return False


